const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const glob = require('glob')
const entry = require('webpack-glob-entry');
const FixStyleOnlyEntriesPlugin = require("webpack-fix-style-only-entries");
const devMode = process.env.NODE_ENV !== 'production'

function getSuffix(str) {
    const index1 = str.lastIndexOf(".");
    const index2 = str.length;
    return str.substring(index1 + 1, index2);
}




// npm run dev --[file]
const npmOriginal = JSON.parse(process.env.npm_config_argv).original;
const FolderPath = npmOriginal[2].slice(2);
const entryJs = {};
const htmlWebpackPlugins = [];
const entryFiles = glob.sync(`./app/${FolderPath}/*.html`);
entryFiles.map((item) => {
    const fileName = item.slice(`./app/${FolderPath}/`.length).slice(0, -5);
    const entryFile = `./app/${FolderPath}/js/${fileName}.js`;
    entryJs[fileName] = entryFile;
    htmlWebpackPlugins.push(
        new HtmlWebpackPlugin({
            template: `./app/${FolderPath}/${fileName}.html`,
            filename: `../${fileName}.html`,
            chunks: [fileName],
            inject: false,
        })
    );
})
/*
const cssFiles = glob.sync(`./app/${FolderPath}/scss/*.{css,scss}`);
cssFiles.map((item) => {
    const suffix = getSuffix(item);
    let num = suffix === 'scss' ? -5 : -4;
    const fileName = item.slice(`./app/${FolderPath}/`.length).slice(0, num);
    // const entryFile = `./app/${FolderPath}/js/${fileName}.${suffix}`;
    // console.log(entryFile)
})
*/

const BUILD_PATH = `dist/${FolderPath}`;
const port = 9000


// yarn run dev --env.[file] = [string]   npm 不行
module.exports = (env) => {
    return [
        {
            entry: entryJs,
            output: {
                path: path.resolve(__dirname, `${BUILD_PATH}/js`),
                publicPath: `${FolderPath}`,
                filename: `[name].js`, // 输出文件名
            },
            module: {
                rules: [
                    {
                        test: /\.js$/,
                        exclude: /(node_modules|bower_components)/,
                        use: {
                            loader: 'babel-loader',
                            options: {
                                presets: ['@babel/preset-env'],
                                plugins: ['@babel/transform-runtime']
                            }
                        }
                    },
                    {
                        test: /\.(html)$/,
                        use: {
                            loader: 'html-loader',
                            options: {
                                attrs: ['img:src', 'img:data-src', 'audio:src'],
                                minimize: true
                            }
                        }
                    },
                    {
                        test: /\.(sa|sc|c)ss$/,
                        exclude: /node_modules/,
                        use: [{
                            loader: MiniCssExtractPlugin.loader,
                        },
                            'css-loader',
                            'sass-loader'
                        ]
                    },
                    {
                        test: /\.(woff|woff2|eot|ttf|otf)$/,
                        use: [
                            'file-loader'
                        ]
                    },
                    {
                        test: /\.(csv|tsv)$/,
                        use: [
                            'csv-loader'
                        ]
                    },
                    {
                        test: /\.(png|svg|jpg|gif)$/,
                        use: [
                            {
                                loader: 'file-loader',
                                options: {
                                    outputPath: '../img',
                                    publicPath: `//cdn.lexue.com:${port}/${FolderPath}/img`,
                                    name: '[name].[ext]'
                                }
                            }
                        ]
                    }
                ]
            },
            devtool: 'inline-source-map',
            devServer: {
                openPage: `${FolderPath}`,
                disableHostCheck: true,
                port: port
            },
            optimization: {
                concatenateModules: false,
                minimize: true,
                minimizer: [new UglifyJsPlugin({
                    include: /\.min\.js$/
                })]
            },
            plugins: [
                // new webpack.optimize.ModuleConcatenationPlugin(),
                new webpack.DefinePlugin({
                    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
                }),
                new MiniCssExtractPlugin({
                    hmr: true,
                    filename: `../css/[name].css`,
                })
            ].concat(htmlWebpackPlugins),
        }
    ]
}
;
